<?php
/**
 *   Joomdiet - administrator/components/com_joomdiet/models/dietmanager.php
 *   Author: Juan Dapena Paz (juan@bittingbits.com)
 *   Copyright (C) 2011 Bitting Bits S.L.
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.model');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
jimport('joomla.utilities.date');

class JoomdietModelDietmanager extends JModel
{
    var $_diet;
    var $_data;
    var $_pagination;
    var $_message = '';
    
    function __construct()
    {
        parent::__construct();
        
        global $mainframe, $option;
        
        try {
            $array = JRequest::getVar('cid', 0, '', 'array');
            $this->setId((int)$array[0]);
        } catch (Exception $e) {
            // do nothing
        }
        
        // loading pagination support
        $limit = $mainframe->getUserStateFromRequest('global.list.limit',
                                                     'limit',
                                                     $mainframe->getCfg('list_limit'),
                                                     'int');
        $limitstart = JRequest::getVar('limitstart', 0, '', 'int');
        $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
        $this->setState('limit', $limit);
        $this->setState('limitstart', $limitstart);
    }
    
    function _buildQuery()
    {
        $this->_query = 'SELECT * FROM #__joomdiet_Diet';
        return $this->_query;
    }
    
    function setId($id)
    {
        $this->_id = $id;
        $this->_diet = null;
    }
    
    function getData()
    {
        if (empty($this->_data)) {
            $query = $this->_buildQuery();
            if (empty($this->_pagination)) {
                $this->_data = $this->_getList($query);
            } else {
                $this->_data = $this->_getList($query, 
                                               $this->getState('limitstart'),
                                               $this->getState('limit'));
            }
            if (empty($this->_data)) $this->_data = array();
        }
        
        return $this->_data;
    }
  
    function getPagination()
    {
        if (empty($this->_pagination)) {
            jimport('joomla.html.pagination');
            $this->_pagination = new JPagination($this->getTotal(),
                                                 $this->getState('limitstart'),
                                                 $this->getState('limit'));
        }
        
        return $this->_pagination;
    }
    
    function getTotal()
    {
        if (empty($this->_total)) {
            $query = $this->_buildQuery();
            $this->_total = $this->_getListCount($this->_query);
        }
        return $this->_total;
    }
    
    function getDiet()
    {
        if ($this->_loadDiet()) {
        } else $this->_initDiet();
        
        return $this->_diet;
    }
    
    function _loadDiet()
    {
        if (empty($this->_diet)) {
            $query = 'SELECT * FROM #__joomdiet_Diet WHERE id='.$this->_id;
            $this->_db->setQuery($query);
            $this->_diet = $this->_db->loadObject();
            
            return (boolean) $this->_diet;
        }
    }
    
    function _initDiet()
    {
        if (empty($this->_diet)) {
            $diet = new StdClass();
            $diet->id = 0;
            $diet->name = null;
            $diet->description = '';
            $diet->file_url = null;
            
            $this->_diet = $diet;
            return (boolean) $this->_diet;
        }
        
        return true;
    }
    
    function _actualFileUrl() {
        if (empty($this->_diet)) {
            return '';
        } else {
            $query = 'SELECT file_url FROM #__joomdiet_Diet WHERE id='.$this->_id;
            $this->_db->setQuery($query);
            return $this->_db->loadResult();
        }
    }
    
    function _checkFile($file) {
        if (!is_array($file)) {
            $this->_message .= JText::_('COM_JOOMDIET_FILE_DOES_NOT_UPLOAD');
            return false;
        }
        
        if ($file['error'] || ($file['size'] < 1)) {
            $this->_message .= JText::_('COM_JOOMDIET_FILE_DOES_NOT_EXIST');
            return false;
        }
        
        $ext = JFile::getExt($file['name']);
        if (strtolower($ext) != 'pdf') {
            $this->_message .= JText::_('COM_JOOMDIET_FILE_IS_NOT_A_PDF');
            return false;
        }
        
        return true;
    }
    
    function _calc_dest($file_entry, $safefilename) {
        $params =& JComponentHelper::getParams('joomdiet');
        $url = $params->get('upload_url');
        
        $safefilename = 
            $this->_recalc_dest_file_name($file_entry, $safefilename);
        $file_entry->file_name = $safefilename;
        
        if (($url == '') || (!JFolder::exists($url))) {
            return COM_JOOMDIET_UPLOAD_DIR.DS.$safefilename;
        } else return $url.DS.$safefilename;
    }
    
    function _check_replace_file($file_entry, $dest) {
        if ($file_entry->id > 0) {
            if ($file_entry->file_url != $dest) {
                JFile::delete($file_entry->file_url);
            }
        }
    }
    
    function _recalc_dest_file_name($file_entry, $filename) {
        if ($file_entry->id == 0) { // only recalc on new files to upload
            $striped_file_name = JFile::stripExt($filename);
            $files = JFolder::files(COM_JOOMDIET_UPLOAD_DIR, $striped_file_name, 
                                    false, false, false);
            if (count($files) == 0) return $filename;
            
            $counter = count($files);
            while (JFile::exists(COM_JOOMDIET_UPLOAD_DIR.DS.
                                 $striped_file_name.'('.$counter.').'.
                                 JFile::getExt($filename))) {
                $counter++;
            }
            return $striped_file_name.'('.$counter.').'.JFile::getExt($filename);
            
        } else return $filename; // if exists on database only replace the file
    }
    
    function _generate_thumb($file_name)
    {
        exec('gs -q -dBATCH -dNOPAUSE -g600x800 -sDEVICE=jpeg -sOutputFile='.
             COM_JOOMDIET_THUMBS_DIR.DS.JFile::stripExt($file_name).'.jpg '.
             COM_JOOMDIET_UPLOAD_DIR.DS.$file_name);
    }
    
    function store()
    {
        $this->getDiet();
        
        $row =& $this->getTable('diet');
        $row->id = JRequest::getVar('diet_id');
        $row->name = JRequest::getVar('diet_name');
        $row->description = JRequest::getVar('diet_description');
        $row->highlighted = JRequest::getVar('diet_highlighted');
        
        $file = JRequest::getVar('diet_file_url', null, 'files', 'array');
        if (($row->id == 0) || ((is_array($file)) && ($file['name'] != '')) ) {
            $row->upload_datetime = JFactory::getDate()->toMySQL();
            if (!$this->_checkFile($file)) JError::raiseError(500, $this->_message);
            $safefilename = JFile::makeSafe($file['name']);
            
            /* calc destination and check if file entry exists on database to
            perform a file replacement */
            $dest = $this->_calc_dest($row, $safefilename);
            $this->_check_replace_file($row, $dest);
            
            if (JFile::upload($file['tmp_name'], $dest)) {
                $row->file_url = $dest;
                $row->file_size = $file['size'];
                if (!$row->file_name) $row->file_name = $file['name'];
                $this->_generate_thumb($row->file_name);
            } else JError::raiseError(500, JText::_('ERROR_IN_UPLOAD').': '.$dest);
        }
        
        if (!$row->store()) {
            return JError::raiseError( 500, $row->getError());
        }
        
        if (!$row->id) {
            return $row->_db->insertid();
        } else return $row->id;
    }
    
    function remove()
    {
        $row =& $this->getTable('diet');
        $row->load($this->_id);
        
        if ($row->file_url) {
            JFile::delete($row->file_url);
            JFile::delete(COM_JOOMDIET_THUMBS_DIR.DS.JFile::stripExt($row->file_name).'.jpg');
        }
        
        $row->delete($this->_id);
    }
    
    function file_to_read()
    {
        // loading file record
        $this->setId(JRequest::getVar('diet_id'));
        $diet = $this->getDiet();
        
        if ($diet && ($diet->file_url != '')) {
            return $diet;
        } else return false;
    }
}
?>
